package com.hmdp.controller;


import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.service.IShopTypeService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@RestController
@RequestMapping("/shop-type")
public class ShopTypeController {
    @Resource
    private IShopTypeService typeService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("list")
    public Result queryTypeList() {
        List<ShopType> typeList;
        List<String> sList = stringRedisTemplate.opsForList().range("cache:shop-type:list", 0, -1);
        // 1. 判断缓存中是否存在
        if(!sList.isEmpty()) {
            System.out.println("go cache list");
            typeList = sList.stream().map((item) -> {
                return JSONUtil.toBean(item, ShopType.class);
            }).collect(Collectors.toList());
            return Result.ok(typeList);
        }
        // 2. 如果不存在查询MySQL
        typeList = typeService.query().orderByAsc("sort").list();
        // 3. 添加数据库
        sList = typeList.stream().map(JSONUtil::toJsonStr).collect(Collectors.toList());
        for(String s: sList) {
            stringRedisTemplate.opsForList().leftPush("cache:shop-type:list", s);
        }
        return Result.ok(typeList);
    }
}
